using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using server.Extensions;
namespace server.Models;

public class Book
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    [Key]
    public int ID { get; set; }
    [RequiredAttribute]
    public string BookName { get; set; } = null!;
    public string? Publisher { get; set; } = null;
    public string? Author { get; set; } = null;
    public string? IndexNo { get; set; } = null;
    [Required]
    public int TotalCount { get; set; } = 1;
    [Required]
    public int AvailableCount { get; set; } = 1;
    public string? Comments { get; set; } = null;
    public DateTime InDate { get; set; }

    // public string BookIdString => $"YS{BookID.ToString().PadLeft(4, '0')}";

    public Book()
    {

    }
    public Book(NewBook template)
    {
        BookName = template.BookName;
        Author = template.Author;
        Publisher = template.Publisher;
        IndexNo = template.IndexNo;
        TotalCount = template.TotalCount;
        AvailableCount = template.AvailableCount;
    }

    public void Update(NewBook new_book){
        // System.Console.WriteLine("update book");
        var props= typeof(NewBook).GetProperties();
        foreach(var p in props){
            var new_val=p.GetValue(new_book);

            var source_prop=typeof(Book).GetProperty(p.Name);
            if (source_prop is null)
            {
                throw new NullReferenceException($"Book has no property:"+p.Name);
            }
            var old_val=source_prop.GetValue(this);
            // System.Console.WriteLine($"{p.Name},{old_val},{new_val}");
            if (new_val != old_val)
            {
                source_prop.SetValue(this,new_val);
            }
        }
    }
}


public class NewBook
{
    [Required]
    [Field(FieldType.String, "书名", true)]
    public string BookName { get; set; } = null!;
    [Field(FieldType.String, "出版商")]
    public string? Publisher { get; set; } = null;
    [Field(FieldType.String, "作者")]
    public string? Author { get; set; } = null;
    [Field(FieldType.String, "索引号")]
    public string? IndexNo { get; set; } = null;
    [Field(FieldType.Integer, "库存数量", true)]
    [Required]
    public int TotalCount { get; set; } = 1;

    [Field(FieldType.Integer, "可借数量", true)]
    [Required]
    public int AvailableCount { get; set; } = 1;
}